package io.yizoo.core;

import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.teaopenapi.models.Config;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import io.elm.core.saas.DSContext;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginDingtalkService {
    Logger logger = org.slf4j.LoggerFactory.getLogger(LoginDingtalkService.class);
    public Client authClient(String key) throws Exception {
        LoadingCache<String, Client> loadingCache = CacheBuilder.newBuilder()
                .expireAfterWrite(2, TimeUnit.HOURS)
                .build(new CacheLoader<String, Client>() {
                    @Override
                    public Client load(String s) throws Exception {
                        Config config = new Config();
                        config.protocol = "https";
                        config.regionId = "central";
                        return new Client(config);
                    }
                });
        return loadingCache.getUnchecked(key);
    }

    public String getAccessToken(String key) {
        LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder()
                .maximumSize(DSContext.DATA_SET.size())
                .expireAfterWrite(2, TimeUnit.HOURS)
                .build(new CacheLoader<String, String>() {
                    @Override
                    public String load(String s) throws Exception {
                        Map<String, Object> dingTalkConfig = ConfigUtil.getConfig(key);
                        String clientId = (String) dingTalkConfig.getOrDefault("client_id", "");
                        String secret = (String) dingTalkConfig.getOrDefault("secret", "");
                        com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
                                .setAppKey(clientId)
                                .setAppSecret(secret);
                        try {
                            Client client = authClient(key);
                            GetAccessTokenResponse response = client.getAccessToken(getAccessTokenRequest);
                            return response.getBody().getAccessToken();
                        } catch (Exception e) {
                            logger.error("获取 access token 失败 错误原因：", e);
                            return null;
                        }
                    }
                });
        return loadingCache.getUnchecked(key);
    }
}
